import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes'
import { getUserInfo, signinRedirect, signoutRedirect } from '@/utils/oidc/index.js'
// import { AREA_LIST, getAreaList } from '@/utils/dictionary.js'
import { AREA_LIST } from '@/utils/dictionary.js'

export function createPermissionGuard(router) {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  router.beforeEach(async(to, from, next) => {
    const oidcUser = await getUserInfo()
    if (oidcUser) {
      const hasRoutes = !!permissionStore.permissionRoutes.length
      // if (!AREA_LIST.value.length) { await getAreaList() }
      if (hasRoutes) {
        next()
      } else {
        try {
          const { VITE_CLIENT_ID } = import.meta.env
          const clientRoleList = oidcUser.profile?.clientRoleList || [{ roleId: null }]
          const { roleId } = clientRoleList.length > 1 ? clientRoleList?.find((item) => item.clientId === VITE_CLIENT_ID) || { roleId: null } : (clientRoleList || { roleId: null })
          const routes = await permissionStore.generateRoutes(roleId)
          const code = await userStore.getUserInfos()
          // const userRole = userStore.userInfo.type // 开发时模拟, 生产时调接口await userStore.getUserInfo()
          // const roleList = { 1: 'superAdmin', 2: 'admin', 3: 'user' }
          // const routes = await permissionStore.generateRoutesMock(['superAdmin'])
          // 没有授权菜单 不跳转
          if (routes.length && !code) {
            routes.forEach((item) => {
              router.addRoute(item)
            })
            router.addRoute(NOT_FOUND_ROUTE)
            router.addRoute(REDIRECT_ROUTE)
            next({ ...to, replace: true })
          } else {
            $message.error('暂无权限访问，请联系管理员')
            setTimeout(() => {
              signoutRedirect()
            }, 500)
          }
        } catch (error) {
          signinRedirect()
        }
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        signinRedirect()
      }
    }
  })
}
